package com.simen.hellobytes;


import com.simen.hellobytes.platform.Platform;

import java.io.File;
import java.util.Locale;

/**
 * @author Created by Simen.
 * @date 创建日期 2018/11/9 17:57
 * @modify 修改者 Simen
 */
public class FileUtil {

    private static final long KB=1024;
    private static final long MB=KB*1024;
    private static final long GB=MB*1024;
    private static final long TB=GB*1024;

    /**
     * 将文件路径转为当前平台格式
     *
     * @param filePath
     * @return
     */
    public static String formatFilePath(String filePath) {
        if (StringUtil.isEmpty(filePath)) {
            return null;
        }

        return filePath.replace('\\', File.separatorChar)
                .replace('/', File.separatorChar);
    }

    /**
     * 将文件路径转为指定平台格式
     *
     * @param filePath
     * @param systemType {@link SystemUtil#getSystemType()}
     * @return
     */
    public static String formatFilePath(String filePath, Platform systemType) {
        if (StringUtil.isEmpty(filePath)) {
            return null;
        }

        if (systemType == Platform.WINDOWS) {
            return filePath.replace('/', '\\');
        } else if (systemType == Platform.OSX
                || systemType == Platform.LINUX) {
            return filePath.replace('\\', '/');
        }

        return filePath;
    }

    public static String toFileSizeString(long fileSize){
        if(fileSize==-1){
            return "";
        }

        if(fileSize<KB){
            return fileSize+"byte";
        }else if(fileSize<MB){
            return formatFileSize(fileSize*1.0/KB)+"K";
        }else if(fileSize<GB){
            return formatFileSize(fileSize*1.0/MB)+"M";
        }else if(fileSize<TB){
            return formatFileSize(fileSize*1.0/GB)+"G";
        }else{
            return formatFileSize(fileSize*1.0/TB)+"T";
        }
    }

    private static String formatFileSize(double fileSize){
        return String.format(Locale.getDefault(),"%.2f",fileSize);
    }

    /**
     * @return 返回文件扩展名(不包含 .)
     */
    public static String getFileExt(String filePath){
        if(filePath==null) return null;
        File file = new File(filePath);
        return getFileExtFromFileName(file.getName());
    }

    public static String getFileExtFromFileName(String fileName){
        if(fileName==null) return null;

        if(fileName.contains(".")){
            return fileName.substring(fileName.indexOf(".")+1);
        }
        return "";
    }

}
